package com.kdgc.power.gen;


import lombok.Setter;
import org.beetl.sql.gen.BaseProject;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.Writer;


@Setter
public class MavenProject extends BaseProject {

 private    String basePackage = "com.kdgc.power";
 private   String child;

    public MavenProject(String root, String child) {
        this.root = root;
        this.child = child;
    }


    @Override
    public Writer getWriterByName(String sourceBuilderName, String targetName) {
        String home = this.root;
        FileWriter writer = null;
        if (sourceBuilderName.equals("md")) {
            String src = this.root + File.separator + "src/main/resources/sql";
            String output = src + File.separator + targetName;
            try {
                checkFile(output);
                writer = new FileWriter(new File(output));
            } catch (IOException e) {
                throw new IllegalArgumentException(output);
            }
        } else {

            String src = this.root + File.separator + "src/main/java";
            String pkg = getBasePackage(sourceBuilderName);
            String subPath = pkg.replace('.', File.separatorChar);
            String output = src + File.separator + subPath + File.separator + targetName;

            try {
                checkFile(output);
                writer = new FileWriter(output);
            } catch (IOException e) {
                throw new IllegalArgumentException(output, e);
            }

        }
        return writer;

    }

    @Override
    public String getBasePackage(String sourceBuilderName) {
        return basePackage + "." + child + "." + sourceBuilderName;
    }

    protected void checkFile(String filePath) throws IOException {
        File file = new File(filePath);
        File fileParent = file.getParentFile();
        if (!fileParent.exists()) {
            // 创建多级目录
            fileParent.mkdirs();
        }
        if (!file.exists()) {
            //创建文件
            file.createNewFile();
        }
    }

}